﻿using System;

namespace FlickrXplorer.Web
{
  public static class EnumExtensions
  {
    /// <summary>
    /// Toggles an enum's value.
    /// </summary>
    /// <value>
    /// This is useful for two-value enumerations where you want to
    /// quickly toggle from one value to another.
    /// </value>
    /// <param name="value">The enum's current value</param>
    /// <param name="option1">The enum's first value</param>
    /// <param name="option2">The enum's second value</param>
    /// <returns>
    /// <b>option1 </b>if <b>value</b> == <b>option2, </b>or
    /// 
    /// <b>option2 </b>if <b>value == option1</b>
    /// </returns>
    /// <example>
    /// Here is our two-value enum:
    /// <pre>
    /// <c>public enum LightSwitchState : int</c>
    /// <c>{</c>
    /// <c>  SwitchIsOff = 0,</c>
    /// <c>  SwitchIsOn</c>
    /// <c>}</c>
    /// 
    /// </pre>
    /// 
    /// Let's set the value, and switch it.
    /// <pre>
    /// <c>LightSwitchState state = LightSwitchState.SwitchIsOn;</c>
    /// <c>state =</c>
    /// <c>  state.Switch(state, LightSwitchState.SwitchIsOff, LightSwitchState.SwitchIsOn);</c>
    /// 
    /// </pre>
    /// <b>state</b> is now LightSwitchState.SwitchIsOff. It has been
    /// toggled from LightSwitchState.SwitchIsOn.
    /// </example>                                                                              
    public static T Next<T>(this Enum value)
    {
      string[] names = System.Enum.GetNames(value.GetType());
      string currentValueName = value.ToString();

      int selectedIndex = -1;
      for (int counter = 0; counter < names.Length; counter++)
      {
        if (names[counter] == currentValueName)
        {
          selectedIndex = counter;
          break;
        }
      }

      if (selectedIndex + 1 >= names.Length)
      {
        selectedIndex = 0;
      }
      else
      {
        selectedIndex += 1;
      }

      return (T)System.Enum.Parse(value.GetType(), names[selectedIndex]);
    }
  }
}
